package cn.datawin.action;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.GZIPOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.datawin.util.FileUtil;
import com.googlecode.jsonplugin.JSONException;
import com.googlecode.jsonplugin.JSONUtil;

/**
 * 基础控制器
 * @author panmg
 */
public class BaseController {
	 private static final String ENCODING = "UTF-8";  

	@InitBinder
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		CustomDateEditor dateEditor = new CustomDateEditor(format, true);
		binder.registerCustomEditor(Date.class, dateEditor);
	}

	public static void printHTML(HttpServletResponse res, Object html) {
		render(res, html, "text/html;charset=UTF-8");
	};

	public static void printJSON(HttpServletResponse res, Object obj) {
		if (obj instanceof String) {
			render(res, obj, "application/json;charset=UTF-8");
			return;
		}
		try {
			render(res, JSONUtil.serialize(obj), "application/json;charset=UTF-8");
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	private static void render(HttpServletResponse response, Object text, String contentType) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0L);
		response.setContentType(contentType);
		//System.out.println(contentType+"::"+text);
		try {
			response.getWriter().print(text);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载文件
	 * @param response
	 * @param in
	 */
	public static void downFile(HttpServletResponse response, InputStream in, String fileName) {
		response.setContentType("APPLICATION/OCTET-STREAM");
		response.setHeader("Content-Disposition", "attachment; filename=" + fileName );
		try {
			FileUtil.copy(in, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 下载图片
	 * 
	 * @param response
	 * @param in
	 */
	public static void downImg(HttpServletResponse response, InputStream in) {
		response.setHeader("Cache-Control", "no-cache");
		try {
			FileUtil.copy(in, response.getOutputStream());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void sendPage(HttpServletResponse res, String url) throws IOException {
		res.sendRedirect(res.encodeURL(url));
	}

	//用于压缩数据
    public void excute(HttpServletResponse response,String str)
            throws ServletException, IOException {  
        byte[] data = str.getBytes(ENCODING);  
        try {  
            byte[] output = compress(data);  
            // 设置Content-Encoding，这是关键点！
            response.setHeader("Content-Encoding", "gzip");  
            // 设置字符集  
            response.setCharacterEncoding(ENCODING);  
            // 设定输出流中内容长度  
            response.setContentLength(output.length);  
            OutputStream out = response.getOutputStream();  
            out.write(output);  
            out.flush();  
            out.close();  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
    }
    
    private byte[] compress(byte[] data) throws Exception {  
        ByteArrayOutputStream baos = new ByteArrayOutputStream();  
        // 压缩  
        GZIPOutputStream gos = new GZIPOutputStream(baos);  
        gos.write(data, 0, data.length);  
        gos.finish();  
        byte[] output = baos.toByteArray();  
        baos.flush();  
        baos.close();  
        return output;  
    }  

}
